package com.cy.store.service.impl;

import com.cy.store.mapper.DistrictMapper;
import com.cy.store.service.ex.AccessDeniedException;
import com.cy.store.service.ex.AddressNotFoundException;
import com.cy.store.service.ex.DeleteException;
import com.cy.store.domain.Address;
import com.cy.store.domain.User;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.AddressCountLimitException;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UpdateException;
import com.cy.store.service.ex.UsernameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/2/22 19:14
 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DistrictMapper districtMapper;

    /**
     *为了方便日后对用户最大收货地址数量的修改
     * 我们将将用户最大收货地址数量放入配置文件
     */
    @Value("${user.address.max-count}")
    private Integer maxCount;
    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() == 1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        Integer count = addressMapper.countByUid(uid);
        if(count == 0){
            address.setIsDefault(1);
        }
        if(count >= maxCount){
            throw new AddressCountLimitException("用户收货地址超出上限");
        }
        // 补全数据
        address.setProvinceName(districtMapper.findNameByCode(address.getProvinceCode()));
        address.setCityName(districtMapper.findNameByCode(address.getCityCode()));
        address.setAreaName(districtMapper.findNameByCode(address.getAreaCode()));
        address.setUid(uid);
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());
        int rows = addressMapper.insert(address);
        if(rows != 1){
            throw new InsertException("插入收货地址数据时出现未知错误，请联系系统管理员");
        }
        /**
         * 对address对象中的数据进行补全:省市区的名字看前端代码发现前端传递过来的省市区的name分别为:
         * provinceCode,cityCode,areaCode,所以这里可以用address对象的get方法获取这三个的数据
         */



    }

    @Override
    public List<Address> getByUid(Integer uid) {
        return addressMapper.findByUid(uid);
    }

    /**
     * 修改某个用户的某条地址为默认地址
     *
     * @param aid      (地址id)
     * @param uid      (用户id)
     * @param username (操作人)
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
//        1.根据aid查询地址数据
        Address address = addressMapper.findByAid(aid);
        if(address == null){
            throw new AddressNotFoundException("地址数据不存在");
        }
//        2.判断地址是否属于当前用户
        if(!address.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }
//        3.将该用户的所有地址设置为非默认地址
        int rows = addressMapper.updateNonDefault(uid);
        if(rows > 0){
        rows = addressMapper.updateDefaultByAid(aid,username,new Date());
        if(rows!=1){
            throw new UpdateException("更新数据时产生了未知异常");
        }

        }
    }
    @Override
    public Integer delete(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);
        if(result == null){
            throw new AddressNotFoundException("地址数据不存在");
        }
        if(!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }
        int rows = addressMapper.deleteByAid(aid);
        if(rows!= 1){
            throw new DeleteException("删除数据时产生了未知异常");
        }
        if(addressMapper.countByUid(uid)==0){
            throw new AddressNotFoundException("没有默认地址");
        }
        if(result.getIsDefault() == 1){
           Address address = addressMapper.findLastModified(uid);
            rows  = addressMapper.updateDefaultByAid(address.getAid(),username,new Date());
           if (rows != 1){
               throw new UpdateException("更新数据时产生了未知异常");
           }
        }
        return rows ;
    }

    @Override
    public Address getByAid(Integer aid, Integer uid) {
        Address address = addressMapper.findByAid(aid);
        if(address == null){
            throw new AddressNotFoundException("地址数据不存在");
        }
        if(!address.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);

        return address;
    }
}
